#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
const int qx[4]={0,0,1,-1},qy[4]={1,-1,0,0};
struct aa
{
	int map[4][4];
	int x,y,step;
};
bool bb[1000009]={false};
const int ans[4][4]={0,0,0,0,
				     0,1,2,3,
				     0,8,0,4,
				     0,7,6,5};
int find(aa a)
{
	int x=0;
	for (int i=1;i<=3;i++)
		for (int j=1;j<=3;j++)
		x=x*9+a.map[i][j];
	return x%1000007;	
}
bool check(int x,int y)
{
	if (x==0||y==0||x>3||y>3) return false;
	return true;
}
bool pan(aa a)
{
	bool x=true;
	for (int i=1;i<=3;i++)
		for (int j=1;j<=3;j++)
		if (a.map[i][j]!=ans[i][j]) x=false;
	return x;	 
}
int main()
{
	aa a;
	memset(a.map,0,sizeof(a.map));
	char c;
	for (int i=1;i<=3;i++)
	for (int j=1;j<=3;j++)
	{
		scanf("%c",&c);
		a.map[i][j]=c-'0';
		if (a.map[i][j]==0) a.x=i,a.y=j;
	}
	a.step=0;
	bb[find(a)]=true;
	queue<aa> q;
	q.push(a);
	int z=0;
	if (!pan(a))
	while (!q.empty())
	{
		a=q.front();
		q.pop();
		int x=a.x,y=a.y;
		
		for (int i=0;i<4;i++)
		if (check(x+qx[i],y+qy[i]))
		{
			aa b=a;
			b.x=x+qx[i];b.y=y+qy[i];
			swap(b.map[x][y],b.map[b.x][b.y]);
			b.step=a.step+1;
			if (pan(b)) {z=b.step;break;}
			int h;
			if (!bb[h=find(b)]) q.push(b),bb[h]=true;
		}
		if (z) break;
	}
	printf("%d",z);
	return 0;
}
